package cn.stronglink.esm27.collection.iot.devices.esm27.task;

import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.netty.NettyServerHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.iot.devices.esm27.ESM27Server;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.ESM27RequestMessageFactory;

import java.net.InetSocketAddress;

public class PushGasTimer implements Runnable {
    private static Logger logger = LogManager.getLogger(PushGasTimer.class.getName());
    private ESM27Server esm27Server; // esm27服务器
    private byte deviceCode;

    public PushGasTimer(ESM27Server server, byte deviceCode) {
        this.esm27Server = server;
        this.deviceCode = deviceCode;
    }

    @Override
    public void run() {
        try {
            if (esm27Server.isConnection()) {
                byte[] datas = ESM27RequestMessageFactory.createMessage(deviceCode, (byte) 0x0A, null);
                esm27Server.send(datas);
                logger.info("定时获取气体实时数据命令已发送:" + ByteUtil.byteArrToHexString(datas));
                // Thread.sleep(3000);
            }
            if (!NettyServerHandler.channelGroup.isEmpty()) {
                // 循环CHANNEL_MAP发送数据
                for (Channel channel : NettyServerHandler.channelGroup) {
                    InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
                    String clientIp = insocket.getAddress().getHostAddress();
                    byte[] datas = ESM27RequestMessageFactory.createMessage(deviceCode, (byte) 0x0A, null);
                    channel.writeAndFlush(Unpooled.copiedBuffer(datas));
                    logger.info("IP:[" + clientIp + "]定时获取气体实时数据命令已发送:" + ByteUtil.byteArrToHexString(datas));
                }
            } else {
                logger.info("没有连接的TCP客户端");
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }

}
